//
//  YWInputMerchantViewController.m
//  百布业务
//
//  Created by 陈炳桦 on 15/10/27.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//  商户录入

#import "YWInputMerchantViewController.h"
#import "BRPlaceholderTextView.h"
#import "YWUserInfo.h"
#import "YWGroup.h"
#import "YWSampleType.h"
#import "YWArea.h"
#import "YWSelectTableViewController.h"
#import <MBProgressHUD.h>
#import "YWInputMerchant.h"

@interface YWInputMerchantViewController () <UITextFieldDelegate,UITextViewDelegate>

// 标题数组
@property (nonatomic,strong) NSArray *conentArray;

/** 选中的商圈 */
@property (nonatomic,strong) YWGroup *selectGroup;

/** 选中的区域 */
@property (nonatomic,strong) YWArea *selectArea;

/** 选中的经营类型 */
@property (nonatomic,strong) YWSampleType *selectType;

// 提示符
@property (nonatomic,strong) MBProgressHUD *HUD;

// 商户录入记录数组
@property (nonatomic,strong) NSMutableArray *inputArray;

// 保存输入的文本
@property (nonatomic,strong) NSMutableDictionary *contentDic;

@end

@implementation YWInputMerchantViewController

#pragma mark - 懒加载
- (NSArray *)conentArray{
    if (_conentArray == nil) {
        _conentArray = @[@"档口名称",@"商圈",@"区域",@"地址",@"经营类型",@"经营描述",@"联系人",@"电话",@"手机",@"QQ",@"微信"];
    }
    return _conentArray;
}

- (MBProgressHUD *)HUD{
    if (_HUD == nil) {
        _HUD = [[MBProgressHUD alloc] initWithView:self.view];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.margin = 20.f;
        [self.view addSubview:_HUD];
    }
    return _HUD;
}

- (NSMutableArray *)inputArray{
    if (_inputArray == nil) {
        
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [cachePath stringByAppendingPathComponent:@"inputArray.plist"];
        _inputArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        
        if (_inputArray == nil) {
            _inputArray = [NSMutableArray array];
        }
    }
    
    return _inputArray;
}

- (NSMutableDictionary *)contentDic{
    if (_contentDic == nil) {
        _contentDic = [NSMutableDictionary dictionary];
    }
    return _contentDic;
}

- (instancetype)init
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"商户录入";
    self.tableView.contentInset = UIEdgeInsetsMake(-30, 0, 0, 0);

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(summit)];
    
    // 初始化选中数据
    [self setup];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(action:) name:@"YWSelectTableViewController" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditind) name:@"YWInputView" object:nil];
}

- (void)endEditind{
    [self.view endEditing:YES];
}

- (void)setup{
    YWUserInfo *userInfo = [YWUserInfo sharedUseInfo];
    self.selectGroup = [userInfo.groupList firstObject];
    self.selectArea = [userInfo.areaList firstObject];
    self.selectType = [userInfo.sampleTypeList firstObject];
}

// 提交按钮
- (void)summit{

    NSString *name = ((UITextField *)[self.view viewWithTag:1]).text; // 档口名称
    NSString *areaId = self.selectArea.ID; //区域ID
    NSString *groupId = self.selectGroup.ID;    // 商圈ID
    NSString *sampleTypeId = self.selectType.ID;
    NSString *address = ((UITextView *)[self.view viewWithTag:4]).text; // 地址
    NSString *scope = ((UITextView *)[self.view viewWithTag:6]).text;   // 经营描述
    NSString *user = ((UITextField *)[self.view viewWithTag:7]).text;   // 联系人
    NSString *tel = ((UITextField *)[self.view viewWithTag:8]).text;    // 电话
    NSString *mobile = ((UITextField *)[self.view viewWithTag:9]).text; // 手机
    NSString *qq = ((UITextField *)[self.view viewWithTag:10]).text;    // QQ
    NSString *weixin = ((UITextField *)[self.view viewWithTag:11]).text;    // 微信
    
    if ([name isEmpty] || [address isEmpty] || [scope isEmpty]
        || [user isEmpty] || [tel isEmpty] || [mobile isEmpty]) {
        
        self.HUD.labelText = @"请补全相应的信息";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        return;
    }
    
    if ([qq isEmpty] && [weixin isEmpty]) {
        
        self.HUD.labelText = @"QQ和微信至少填一个";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];

        return;
    }
    
    self.HUD.labelText = @"提交中...";
    [self.HUD show:YES];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"name"] = name;
    param[@"tel"] = tel;
    param[@"areaId"] = areaId;
    param[@"groupId"] = groupId;
    param[@"address"] = address;
    param[@"scope"] = scope;
    param[@"sampleTypeId"] = sampleTypeId;
    param[@"user"] = user;
    param[@"mobile"] = mobile;
    param[@"qq"] = qq;
    param[@"weixin"] = weixin;

    
    [YWNetwork addSellerWithParameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"%@",responseObject);
        [self handleResponse:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.HUD.labelText = @"发生未知错误";
        [self.HUD hide:YES afterDelay:2];
    }];
}

- (void)handleResponse:(NSDictionary *)responseObject{
    
    NSNumber *flag = (NSNumber *)responseObject[@"flag"];
    
    if([flag intValue] == 1){  // 登录成功
        self.HUD.labelText = responseObject[@"msg"];
        [self.HUD hide:YES afterDelay:2];
        
        // 保存数据
        YWInputMerchant *input = [[YWInputMerchant alloc] init];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        
        input.date = str;
        input.code = responseObject[@"code"];
        input.password = responseObject[@"password"];
        
        [self.inputArray addObject:input];
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [cachePath stringByAppendingPathComponent:@"inputArray.plist"];
        [NSKeyedArchiver archiveRootObject:self.inputArray toFile:filePath];
        
        // 弹出提示框
        NSString *alertText = [NSString stringWithFormat:@"你的百布易卖账号已开通！\n账号：%@，\n密码：%@，\n如在使用中遇到问题，请联系致电400-068-0040!",responseObject[@"code"],responseObject[@"password"]];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"开通成功" message:alertText preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 返回上一级
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        self.HUD.labelText = responseObject[@"msg"];
        [self.HUD hide:YES afterDelay:2];
    }
}

// 监听到通知
- (void)action:(NSNotification *)notification{
    
    if ([notification.object isKindOfClass:[YWGroup class]]){

        self.selectGroup = notification.object;
        self.selectArea = [[self getArrayWithID:self.selectGroup.ID] firstObject];
        // 刷新指定行
        NSIndexPath *path1 = [NSIndexPath indexPathForRow:1 inSection:0];
        NSIndexPath *path2 = [NSIndexPath indexPathForRow:2 inSection:0];
       [self.tableView reloadRowsAtIndexPaths:@[path1,path2] withRowAnimation:UITableViewRowAnimationRight];
        
    }else if([notification.object isKindOfClass:[YWArea class]]){

        self.selectArea = notification.object;
        // 刷新指定行
        NSIndexPath *path = [NSIndexPath indexPathForRow:2 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationRight];
        
    }else if([notification.object isKindOfClass:[YWSampleType class]]){
        
        self.selectType = notification.object;
        // 刷新指定行
        NSIndexPath *path = [NSIndexPath indexPathForRow:4 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationRight];
    }
}

// 通过商圈ID获取对应的区域数组
- (NSMutableArray *)getArrayWithID:(NSString *)ID{
    YWUserInfo *userInfo = [YWUserInfo sharedUseInfo];
    
    NSMutableArray *array = [NSMutableArray array];
    for (YWArea *area in userInfo.areaList) {
        if ([area.parentId isEqualToString:ID]) {
            [array addObject:area];
        }
    }
    
    return array;
}

#pragma mark - UITextFieldDelegate
// 输入完成后保存到字典中
- (void)textFieldDidEndEditing:(UITextField *)textField{
    // 保存数据
    [self.contentDic setObject:textField.text forKey:@(textField.tag)];
}

#pragma mark - UITextViewDelegate
// 输入完成后保存到字典中
- (void)textViewDidEndEditing:(UITextView *)textView{
    // 保存数据
    [self.contentDic setObject:textView.text forKey:@(textView.tag)];
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3 || indexPath.row == 5) {
        return 100;
    }
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.conentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ID = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    // 取消选中状态
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.textLabel.text = self.conentArray[indexPath.row];
    
    cell.accessoryView = [self getAccessoryView:indexPath.row];
    
    return cell;
}

- (UIView *)getAccessoryView:(NSInteger)index{
    
    
    // 1.AccessoryView是UITextField类的
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 31)];
    textField.placeholder = @"默认";
    textField.inputAccessoryView = [[NSBundle mainBundle] loadNibNamed:@"YWInputView" owner:nil options:nil][0];
    textField.textAlignment = NSTextAlignmentRight;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.tag = index + 1;
    textField.delegate = self;
    textField.text = [self.contentDic objectForKey:@(textField.tag)];
    switch (index) {
        case 0:     // 档口名称
            textField.placeholder = @"请填写档口名称";
            return textField;
            break;
        case 6:     // 联系人
            textField.placeholder = @"请填写联系人";
            return textField;
            break;
        case 7:     // 电话
            textField.placeholder = @"请填写店铺电话";
            return textField;
            break;
        case 8:     // 手机
            textField.placeholder = @"请填写手机";
            return textField;
            break;
        case 9:     // QQ
            textField.placeholder = @"QQ和微信至少填写一个";
            return textField;
            break;
        case 10:     // 微信
            textField.placeholder = @"QQ和微信至少填写一个";
            return textField;
            break;
        default:
            break;
    }
    
    // 2.AccessoryView是BRPlaceholderTextView类(带placeholder的UITextView)的
    BRPlaceholderTextView *textView = [[BRPlaceholderTextView alloc] initWithFrame:CGRectMake(0, 0, 200, 90)];
    textView.inputAccessoryView = [[NSBundle mainBundle] loadNibNamed:@"YWInputView" owner:nil options:nil][0];
    textView.font = [UIFont systemFontOfSize:16];
    textView.textAlignment = NSTextAlignmentRight;
    textView.tag = index + 1;
    textView.delegate = self;
    textView.text = [self.contentDic objectForKey:@(textField.tag)];
    if (index == 3) {
        textView.placeholder = @"格式：如珠江国际纺织城北六街D10801档，只需填写六街D10801档";
        return textView;
    }else if(index == 5){
        textView.placeholder = @"参考格式：针织、雪纺、丝绸。  （注：以、分割，以。结束）";
        return textView;
    }
    
    // 3.AccessoryView是UILabel类
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 31)];
    label.textAlignment = NSTextAlignmentRight;
    label.tag = index + 1;
    if (index == 1) {
//        label.text = @"中大商圈";
        label.text = self.selectGroup.name;
        
    }else if(index == 2){
//        label.text = @"广州国际轻纺城";
        label.text = self.selectArea.name;
    }else if(index == 4){
//        label.text = @"面料";
        label.text = self.selectType.name;
    }
    
    return label;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YWSelectTableViewController *selectVC = [[YWSelectTableViewController alloc] init];
    if (indexPath.row == 1) { // 选择商圈
        selectVC.type = 0;
        [self.navigationController pushViewController:selectVC animated:YES];
    }else if (indexPath.row == 2){  // 选择区域
        selectVC.type = 1;
        selectVC.ID = self.selectGroup.ID;
        [self.navigationController pushViewController:selectVC animated:YES];
    }else if (indexPath.row == 4){  // 选择区域
        selectVC.type = 2;
        [self.navigationController pushViewController:selectVC animated:YES];
    }
    
}

- (void)dealloc{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
